//
//  UIViewController+YSLog.m
//  YSKitExample
//
//  Created by Kyson on 2017/6/16.
//  Copyright © 2017年 YangShen. All rights reserved.
//

#import "UIViewController+YSLog.h"
#import <objc/runtime.h>

static BOOL isSwizzed;
static NSString *logTag = @"";

@implementation UIViewController (YSLog)

+ (void)load {
    isSwizzed = NO;
}

#pragma mark - Util methods
static void ys_swizzInstance(Class class, SEL originalSelector, SEL swizzledSelector) {
    Method originalMethod = class_getInstanceMethod(class, originalSelector);
    Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
    BOOL didAddMethod = class_addMethod(class, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));
    if (didAddMethod) {
        class_replaceMethod(class, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
    } else {
        method_exchangeImplementations(originalMethod, swizzledMethod);
    }
}

- (void)ys_logWithLevel:(NSUInteger)level {
    NSString *paddingItems = @"";
    for (NSUInteger i = 0; i <= level; i++) {
        paddingItems = [paddingItems stringByAppendingFormat:@"--"];
    }
    
    NSLog(@"%@%@-> %@", logTag, paddingItems, [self.class description]);
}

#pragma mark - SwizzMethods
- (void)ys_printPath {
    if ([self parentViewController] == nil) {
        [self ys_logWithLevel:0];
    }
    else if([[self parentViewController] isMemberOfClass:[UINavigationController class]]) {
        UINavigationController *nav = (UINavigationController *)[self parentViewController];
        NSInteger integer = [[nav viewControllers] indexOfObject:self];
        [self ys_logWithLevel:integer];
    }
    else if ([[self parentViewController] isMemberOfClass:[UITabBarController class]]) {
        [self ys_logWithLevel:1];
    }
}

- (void)ys_swizzviewDidAppear:(BOOL)animated {
    [self ys_printPath];
    [self ys_swizzviewDidAppear:animated];
}

#pragma mark - Public methods
+ (void)ys_swizzIt {
    if (isSwizzed) {
        return;
    }
    ys_swizzInstance([self class],@selector(viewDidAppear:),@selector(ys_swizzviewDidAppear:));
    isSwizzed = YES;
}

+ (void)ys_swizzItWithTag:(NSString *)tag {
    logTag = tag;
    [self ys_swizzIt];
}

+ (void)ys_undoSwizz {
    if (!isSwizzed) {
        return;
    }
    
    isSwizzed = NO;
    ys_swizzInstance([self class],@selector(ys_swizzviewDidAppear:),@selector(viewDidAppear:));
}

@end
